package fr.inria.phoenix.scenario.bwsnfirefighting.impl.context;

import fr.inria.diagen.core.ServiceConfiguration;
import fr.inria.diagen.core.exception.InvocationException;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.DangerLevel;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.temperaturedetection.EnvironmentSensorDeviceComposite;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.temperaturedetection.EnvironmentSensorDeviceProxy;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.temperaturedetection.TemperatureDetection;

public class TemperatureDetectionImpl extends TemperatureDetection {

	private int warningBound = 40;
	private int alertBound = 48;
	public TemperatureDetectionImpl(ServiceConfiguration serviceConfiguration) {
		super(serviceConfiguration);
	}

	@Override
	public void onNewTemperature(EnvironmentSensorDeviceProxy proxy,
			Integer newTemperatureValue) {
		EnvironmentSensorDeviceComposite sensors = discover(environmentSensorDevicesWhere().location(proxy.getLocation()));
		DangerLevel temp = DangerLevel.SAFE;
		int numSens = sensors.size() < 4 ? 1 : 3;
		int warnCount = newTemperatureValue > warningBound && newTemperatureValue <= alertBound ? 1 : 0;
		int alertCount = newTemperatureValue > alertBound ? 0 : 1;
		try {
			if (proxy.getDangerousmaterial()){
				for (EnvironmentSensorDeviceProxy sensor : sensors){
					if (sensor.getTemperature() > warningBound && sensor.getTemperature() <= alertBound){
						warnCount++;
					}
					else if (sensor.getTemperature() > alertBound){
							alertCount++;
					}
				}
				if (alertCount >= 1){
					temp = DangerLevel.ALERT;
				}
				else if (warnCount >= 1){
					temp = DangerLevel.WARNING;
				}
				else {
					temp = DangerLevel.SAFE;
				}
			}
			else{
				for (EnvironmentSensorDeviceProxy sensor : sensors){
					if (sensor.getTemperature() > warningBound && sensor.getTemperature() <= alertBound){
						warnCount++;
					}
					else if (sensor.getTemperature() > alertBound){
						alertCount++;
					}
				}
				if (alertCount >= numSens){
					temp = DangerLevel.ALERT;
				}
				else if (warnCount >= numSens){
					temp = DangerLevel.WARNING;
				}
				else {
					temp = DangerLevel.SAFE;
				}
			}
		this.setTemperatureDetection(temp, proxy.getLocation());
		} catch (InvocationException e) {
			e.printStackTrace();
		}
	}

}
